package com.jx.lcs.util.file;

import java.io.BufferedOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;

import javax.servlet.http.HttpServletResponse;

/**
 * 文件下载工具类
 * 
 * @author JiaYY
 * @date 2015年7月17日
 */

public class FileUtil {

	/**
	 * 下载文件
	 * @param urlString
	 * @param response
	 */
	public static void downloadFile(String urlString, HttpServletResponse response) {
		InputStream is = null;
		OutputStream os = null;
		try {
			// 构造URL
			URL url = new URL(urlString);
			// 打开连接
			URLConnection con = url.openConnection();
			// 设置请求超时为5s
			con.setConnectTimeout(5 * 1000);
			// 输入流
			is = con.getInputStream();

			String fileName = new Date().getTime()
					+ urlString.substring(urlString.lastIndexOf("."));

			// 清空response
			response.reset();
			// 设置response的Header
			response.addHeader("Content-Disposition", "attachment;filename="
					+ fileName);
			response.setContentType("application/octet-stream");
			os = new BufferedOutputStream(response.getOutputStream());
			
			 // 读取到的数据长度  
	        int len;
	        // 10K的数据缓冲  
	        byte[] bs = new byte[10240]; 
			// 开始读取  
	        while ((len = is.read(bs)) != -1) {  
	          os.write(bs, 0, len);  
	        }  
			os.flush();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				os.close();
				is.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}
